package com.team.book.handler;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by haolw on 2017/4/7.
 *
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler{
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        HttpSession session = httpServletRequest.getSession();
        session.removeAttribute("errorMsg");
       if (e.getCause() instanceof OAuth2AccessDeniedException) {
            if(e.getMessage().equals("Error requesting access token.")){
                session.setAttribute("errorMsg", "管理员不存在。");
            }else{
                session.setAttribute("errorMsg", "用户名或密码错误。");
            }
            session.setAttribute("logon_failure", 0);
        }else {
            String msg = e.getMessage();
            if(msg == null || msg.equals("user_not_found")){
                session.setAttribute("errorMsg", "管理员不存在。");
            }else{
                session.setAttribute("errorMsg", "用户名或密码错误");
            }
        }
        try {
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
